$(function(){

    if ('' != $('.searchbox input').val())
    {
        $('.searchbox input').addClass('active');
    }
    
//---------------------------------------------------------------------------------------------------------------------
    
    $('.searchbox input').focus(function(){
        $(this).addClass('active');
    });
    
//---------------------------------------------------------------------------------------------------------------------
    
    $('.searchbox input').blur(function(){
        if ('' == $(this).val())
        {
            $(this).removeClass('active');
        }
    });
    
//---------------------------------------------------------------------------------------------------------------------

    attachSearch('.searchbox input');
    
//---------------------------------------------------------------------------------------------------------------------    

    $('.card_list a.card_preview').click(function(){
        return !showCardPreview($(this).parent());
    });
    
    $('.preview a.prev').click(function(){
        var active = $('.card_list').children('.card_small').filter('.active').eq(0);
        var prev = active.prev('.card_small');
        return !showCardPreview(prev);
    });
    
    $('.preview a.next').click(function(){
        var active = $('.card_list').children('.card_small').filter('.active').eq(0);
        var next = active.next('.card_small');
        return !showCardPreview(next);
    });
    
    $('#card_next_step').click(function(){
        var id = $('.preview:first').attr('card_id');
        var size = $('#size_select').val();
        window.location.pathname = '/editor/index/card/' + encodeURIComponent(id) + '/size/' + encodeURIComponent(size);
    });
    
//---------------------------------------------------------------------------------------------------------------------

    $('.menu a').click(function(){
        var nextUl = $(this).siblings('ul').first();
        if (nextUl.size() > 0)
        {
            if (nextUl.is(':visible'))
            {
                nextUl.hide();
            }
            else
            {
                nextUl.show();
            }
            return false;
        }
    });
    
    setInterval(function(){
        if (2 > $('.rotator>a').size()) return;
        var element1 = $('.rotator a').filter(':visible').eq(0);
        var element2 = element1.next('.rotator a');
        if (0 == element2.size())
        {
            element2 = $('.rotator>a:eq(0)');
        }
        var others = $('.rotator a').not(element1).not(element2).filter(':visible');
        element1.fadeOut(1500);
        if (0 != others.size())
        {
            others.fadeOut(10);
        }
        element2.fadeIn(1000);
    },3500);
    
    $('.dropdown').mouseenter(
        function(){
            if ($(this).hasClass('active')) return;
            $(this).addClass('active');
            $('.dropdown>div').not($(this)).filter(':visible').stop().animate({height:'0px', opacity:'0'/*, 'z-index':'9'*/}, {
                queue: false,
                complete:function(){
                    $(this).hide();
                    $(this).parent().removeClass('active');
                }
            });
            $(this).children('div').stop().css({height:'1px', opacity:'0.3'/*, 'z-index':'10'*/}).animate({height:'230px', opacity:'1'}, {
                queue: false,
                duration: 500,
                specialEasing: {
                      opacity: 'linear',
                      height: 'easeOutBounce'
                    }
            });
        });

    $(document).bind('click.menu',function(e){
        if ($(e.target).parents('.dropdown').size() > 0) return true;
        $('.dropdown').children('div').filter(':visible').stop().animate({'height':'0px', 'opacity':'0'/*, 'z-index':9*/}, {
            queue: false,
            complete:function(){
                $(this).hide();
                $(this).parent().removeClass('active');
            }
        });
    });
    
    $(document).bind('click.fav',function(e){
        if ($(e.target).parents('.favorites').size() > 0) return true;
        $('.favorites').children('div.dd').filter(':visible').stop().animate({height:'0px', opacity:'0'/*, 'z-index':9*/}, {
            queue: false,
            complete:function(){
                $(this).hide();
                $(this).parent().removeClass('active');
            }
        });
    });
    
//---------------------------------------------------------------------------------------------------------------------

    $('#add_fav').live('click', function(){
        if( $(this).parent().parent().hasClass('active') )
        {	
        	return false;
        }
        $(this).parent().parent().addClass('active');

        $(this).parent().siblings('div.dd').stop().css({height:'1px', opacity:'0.3', 'z-index':'10'}).animate({height:'230px', opacity:'1'}, 
        {
            queue: false,
            duration: 500,
            specialEasing: 
            {
                  opacity: 'linear',
                  height: 'easeOutBounce'
            }
        });
        return false;
    });
    
//---------------------------------------------------------------------------------------------------------------------

    $('#add_fav_submit').live('click', function()
	{ 
    
    	$('#id_fav_item').val($('.preview').attr('card_id'));
    	
    	var id_fav_item 	 = $('.preview').attr('card_id');
    	var	new_fav_category = $('#new_fav_category').val();
    	var fav_category	 = $('#fav_category').val();
    	
		$.ajax(
		{
			type: 'POST',
			url: '/favorites/add',
			data: 'id_fav_item=' + encodeURIComponent( id_fav_item ) + 
				  '&new_fav_category=' + encodeURIComponent( new_fav_category ) +
				  '&fav_category=' + encodeURIComponent( fav_category ),
			dataType: 'json',
			success: function(r)
			{
			  if (1 == r.ret)
			  {
				  $('#new_fav_category').val('');
				  $('.favorites .dd').stop().animate({height:'0px', opacity:'0', 'z-index':'9'}, {
			            queue: false,
			            complete:function(){
			                $(this).hide();
			            }
			        });
				  
				  $('.favorites .dd').parent().removeClass('active');
				  $('#a_add_fav').html(' <a href="#" id="remove_fav">Remove from favorites</a> ');
				  $('.card_preview').filter('[card_id=' + id_fav_item + ']').attr('favorite_id', r.fav_id);
			  }
			}
		});	
    	
    });

 //---------------------------------------------------------------------------------------------------------------------

    $('#remove_fav').live('click', function(){
    
    	var id_fav_item 	 = $('.preview').attr('card_id');

    	$.ajax(
		{
			type: 'POST',
			url: '/favorites/remove',
			data: 'id_fav_item=' + encodeURIComponent( id_fav_item ),
			dataType: 'json',
			success: function(r)
			{
			  if (1 == r.ret)
			  {
				  $('#a_add_fav').html(' <a href="#" id="add_fav">Add to favorites</a> ');
				  $('.favorites .dd').parent().removeClass('active');
				  $('.card_preview').filter('[card_id=' + id_fav_item + ']').removeAttr('favorite_id');
				  if($('#title_append').text() != '')
				  {
					  $('.preview img').attr('src', '');
					  $('.id_fav_item_' + id_fav_item).remove();
					  showCardPreview($('.card_small:visible:first'));
				  }
			  }
			}
		});
    
    });
    
//---------------------------------------------------------------------------------------------------------------------

    $('.filter').click(function(){
    	var filter = $(this).text();
    	$(this).siblings('.filter').removeClass('active');
    	$(this).addClass('active');
		$('.filtered').show();
		if ('All' != filter)
		{
			$('.filtered').not('.filtered' + filter + 'letter').hide();
		}
    });
    
    $('#selectAll').click(function(){
		$('.filtered:visible input[type="checkbox"]').attr('checked', 'checked');
    });
    
    $('#deselectAll').click(function(){
		$('.filtered:visible input[type="checkbox"]').attr('checked', '');
    });
    
    $('#deleteSelected').click(function(){
    	var ids = '';
		$('.filtered:has(input[type="checkbox"][checked!=""])').each(function(){
			ids += 'id[]=' + encodeURIComponent($(this).attr('item_id')) + '&';
		});
		$.ajax({
			type: 'POST',
			url: '/address/delete',
			data: ids + 'delete=1',
			dataType: 'json',
			success: function(r)
			{
			  if (1 == r.ret)
			  {
				  for (id in r.ids)
				  {
					  var item = $('div[item_id="' + r.ids[id] + '"]');
					  item.slideUp('fast', function(){ item.remove(); });
				  }
			  }
			}
		});
    });
    
    if (0 != $('#is_bfpo').length)
    {
    	if ($('#is_bfpo').attr('checked'))
    	{
    		$('.regular_address').hide();
    		$('.bfpo_address').show();
    	}
    	else
    	{
    		$('.bfpo_address').hide();
    		$('.regular_address').show();
    	}
    }
    
    $('#is_bfpo').click(function(){
    	resetBFPO();
    });
    
  //---------------------------------------------------------------------------------------------------------------------

    $('.selectable').click(function(event){
    	if (!event.ctrlKey)
    	{
    		$(this).siblings('.selectable').removeClass('selected');
    	}
    	$(this).toggleClass('selected');
    });
    
    $('a.sexybutton').mouseup(function(){$(this).blur();});
    
    $('#ml_add').click(function(){
    	var items = new Array();
    	$('.address_list .selected').each(function(){
    		$('.mailinglist_list').append($(this).removeClass('selected'));
    		items.push($(this).attr('item_id'));
    	});
    	mailingListAddItem(items);
    	return false;
    });
    
    $('#ml_addall').click(function(){
    	var items = new Array();
    	$('.address_list .selectable').each(function(){
    		$('.mailinglist_list').append($(this).removeClass('selected'));
    		items.push($(this).attr('item_id'));
    	});
    	mailingListAddItem(items);
    	return false;
    });
    
    $('#ml_remove').click(function(){
    	var items = new Array();
    	$('.mailinglist_list .selected').each(function(){
    		$('.address_list').append($(this).removeClass('selected'));
    		items.push($(this).attr('item_id'));
    	});
    	mailingListDeleteItem(items);
    	return false;
    });
    
    $('#ml_removeall').click(function(){
    	var items = new Array();
    	$('.mailinglist_list .selectable').each(function(){
    		$('.address_list').append($(this).removeClass('selected'));
    		items.push($(this).attr('item_id'));
    	});
    	mailingListDeleteItem(items);
    	return false;
    });
    
    $('#ml_removeall').click(function(){
    	var items = new Array();
    	$('.mailinglist_list .selectable').each(function(){
    		$('.address_list').append($(this).removeClass('selected'));
    		items.push($(this).attr('item_id'));
    	});
    	mailingListDeleteItem(items);
    	return false;
    });
    
    $('.delete_mlist').click(function(){
    	var item = $(this).parents('.mailinglist').eq(0);
    	var id = item.attr('item_id');
    	item.remove();
    	mailingListDelete(id);
    });
    
//---------------------------------------------------------------------------------------------------------------------
    
    start();
    
//---------------------------------------------------------------------------------------------------------------------

});        // ------------------ MAIN ------------------ 

function mailingListDelete( listId )
{
	$.ajax(
	{
		type: 'POST',
		url: '/mailinglist/delete',
		data: 'list_id=' + encodeURIComponent( listId ),
		dataType: 'json',
		success: function(r)
		{
		  
		}
	});
}

function mailingListAddItem( items )
{
	if (0 == items.length) return false;
	var listId = parseInt($('.mailinglist_list').attr('list_id'));
	$.ajax(
	{
		type: 'POST',
		url: '/mailinglist/additem',
		data: 'items=' + encodeURIComponent( items.join(';') ) + 
			  '&list_id=' + encodeURIComponent( listId ),
		dataType: 'json',
		success: function(r)
		{
		  
		}
	});
}

function mailingListDeleteItem( items )
{
	if (0 == items.length) return false;
	var listId = parseInt($('.mailinglist_list').attr('list_id'));
	$.ajax(
	{
		type: 'POST',
		url: '/mailinglist/deleteitem',
		data: 'items=' + encodeURIComponent( items.join(';') ) + 
			  '&list_id=' + encodeURIComponent( listId ),
		dataType: 'json',
		success: function(r)
		{
		  
		}
	});
}

function resetBFPO()
{
	if ($('#is_bfpo').attr('checked'))
	{
		$('.regular_address').hide();
		$('.bfpo_address').show();
	}
	else
	{
		$('.bfpo_address').hide();
		$('.regular_address').show();
	}
}

function start()
{
    var activeCard = $('.card_list .card_small.active');
    if (activeCard.size() == 0)
    {
    	activeCard = $('.card_list .card_small:first');
    }
    if (activeCard.size() != 0)
    {
    	showCardPreview(activeCard);
    }
}

function showCardPreview(element)
{
    if (element.size() > 0)
    {
        $('.card_list').children('.card_small').removeClass('active');
        element.addClass('active');
        var a = element.find('a').eq(0);
        $('.preview img').attr('src', a.attr('href'));
        $('.preview').attr('card_id', a.attr('card_id'));
        $('.preview').attr('favorite_id', a.attr('favorite_id'));
        var favorite_id 	= $('.preview').attr('favorite_id');
        
        var category_name 	=  a.attr('category_name');
        
        var tags		 	=  a.attr('tags');
        $('#card_tags').html('');
        if ('' != tags)
        {
        	var tagsArray = tags.split('|');
        	var taglist = '';
        	for (var i in tagsArray)
        	{
        		taglist += '<a href="/search/index/tag/' + tagsArray[i] +'">' + tagsArray[i] +'</a> ';
        	}
        	$('#card_tags').html(taglist);
        }
        
        if(favorite_id == '')
        {
			  $('#a_add_fav').html(' <a href="#" id="add_fav">Add to favorites</a> ');
        }
        else
        {
			  $('#a_add_fav').html(' <a href="#" id="remove_fav">Remove from favorites</a> ');
        }
        if(category_name != '')
        {
			  $('#title_append').text(' - ' + category_name);
        }
        
        return true;
    }
    else
    {
        return false;
    }
}

function attachSearch(element)
{
    $(element).keypress(function(event){
        if (event.which == 13)
        {
            $(this).siblings('.button').click();
        }
    });
    $(element).siblings('.button').click(function(event){
        var words = $(element).val();
        window.location = "/search/index/words/" + encodeURIComponent( words );
    });
}

//---------------------------------------------------------------------------------------------------------------------


//---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

function sprintf( ) {	// Return a formatted string
	// 
	// +   original by: Ash Searle (http://hexmen.com/blog/)
	// + namespaced by: Michael White (http://crestidg.com)

	var regex = /%%|%(\d+\$)?([-+#0 ]*)(\*\d+\$|\*|\d+)?(\.(\*\d+\$|\*|\d+))?([scboxXuidfegEG])/g;
	var a = arguments, i = 0, format = a[i++];

	// pad()
	var pad = function(str, len, chr, leftJustify) {
		var padding = (str.length >= len) ? '' : Array(1 + len - str.length >>> 0).join(chr);
		return leftJustify ? str + padding : padding + str;
	};

	// justify()
	var justify = function(value, prefix, leftJustify, minWidth, zeroPad) {
		var diff = minWidth - value.length;
		if (diff > 0) {
			if (leftJustify || !zeroPad) {
			value = pad(value, minWidth, ' ', leftJustify);
			} else {
			value = value.slice(0, prefix.length) + pad('', diff, '0', true) + value.slice(prefix.length);
			}
		}
		return value;
	};

	// formatBaseX()
	var formatBaseX = function(value, base, prefix, leftJustify, minWidth, precision, zeroPad) {
		// Note: casts negative numbers to positive ones
		var number = value >>> 0;
		prefix = prefix && number && {'2': '0b', '8': '0', '16': '0x'}[base] || '';
		value = prefix + pad(number.toString(base), precision || 0, '0', false);
		return justify(value, prefix, leftJustify, minWidth, zeroPad);
	};

	// formatString()
	var formatString = function(value, leftJustify, minWidth, precision, zeroPad) {
		if (precision != null) {
			value = value.slice(0, precision);
		}
		return justify(value, '', leftJustify, minWidth, zeroPad);
	};

	// finalFormat()
	var doFormat = function(substring, valueIndex, flags, minWidth, _, precision, type) {
		if (substring == '%%') return '%';

		// parse flags
		var leftJustify = false, positivePrefix = '', zeroPad = false, prefixBaseX = false;
		for (var j = 0; flags && j < flags.length; j++) switch (flags.charAt(j)) {
			case ' ': positivePrefix = ' '; break;
			case '+': positivePrefix = '+'; break;
			case '-': leftJustify = true; break;
			case '0': zeroPad = true; break;
			case '#': prefixBaseX = true; break;
		}

		// parameters may be null, undefined, empty-string or real valued
		// we want to ignore null, undefined and empty-string values
		if (!minWidth) {
			minWidth = 0;
		} else if (minWidth == '*') {
			minWidth = +a[i++];
		} else if (minWidth.charAt(0) == '*') {
			minWidth = +a[minWidth.slice(1, -1)];
		} else {
			minWidth = +minWidth;
		}

		// Note: undocumented perl feature:
		if (minWidth < 0) {
			minWidth = -minWidth;
			leftJustify = true;
		}

		if (!isFinite(minWidth)) {
			throw new Error('sprintf: (minimum-)width must be finite');
		}

		if (!precision) {
			precision = 'fFeE'.indexOf(type) > -1 ? 6 : (type == 'd') ? 0 : void(0);
		} else if (precision == '*') {
			precision = +a[i++];
		} else if (precision.charAt(0) == '*') {
			precision = +a[precision.slice(1, -1)];
		} else {
			precision = +precision;
		}

		// grab value using valueIndex if required?
		var value = valueIndex ? a[valueIndex.slice(0, -1)] : a[i++];

		switch (type) {
			case 's': return formatString(String(value), leftJustify, minWidth, precision, zeroPad);
			case 'c': return formatString(String.fromCharCode(+value), leftJustify, minWidth, precision, zeroPad);
			case 'b': return formatBaseX(value, 2, prefixBaseX, leftJustify, minWidth, precision, zeroPad);
			case 'o': return formatBaseX(value, 8, prefixBaseX, leftJustify, minWidth, precision, zeroPad);
			case 'x': return formatBaseX(value, 16, prefixBaseX, leftJustify, minWidth, precision, zeroPad);
			case 'X': return formatBaseX(value, 16, prefixBaseX, leftJustify, minWidth, precision, zeroPad).toUpperCase();
			case 'u': return formatBaseX(value, 10, prefixBaseX, leftJustify, minWidth, precision, zeroPad);
			case 'i':
			case 'd': {
						var number = parseInt(+value);
						var prefix = number < 0 ? '-' : positivePrefix;
						value = prefix + pad(String(Math.abs(number)), precision, '0', false);
						return justify(value, prefix, leftJustify, minWidth, zeroPad);
					}
			case 'e':
			case 'E':
			case 'f':
			case 'F':
			case 'g':
			case 'G':
						{
						var number = +value;
						var prefix = number < 0 ? '-' : positivePrefix;
						var method = ['toExponential', 'toFixed', 'toPrecision']['efg'.indexOf(type.toLowerCase())];
						var textTransform = ['toString', 'toUpperCase']['eEfFgG'.indexOf(type) % 2];
						value = prefix + Math.abs(number)[method](precision);
						return justify(value, prefix, leftJustify, minWidth, zeroPad)[textTransform]();
					}
			default: return substring;
		}
	};

	return format.replace(regex, doFormat);
}
